package monitor

import (
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
)

// ApiCounter 统计api的调用情况
var ApiCounter = prometheus.NewCounterVec(
	prometheus.CounterOpts{
		Name: "api_access_counter",
		Help: "access count of api.",
	},
	[]string{"method", "path", "result"},
)

// HttpDurations 接口耗时统计
var HttpDurations = prometheus.NewSummaryVec(
	prometheus.SummaryOpts{
		Name:       "http_durations_seconds",
		Objectives: map[float64]float64{0.9: 0.01},
	},
	[]string{"method", "path"},
)

// ApiRateLimiterCounter api限流次数统计
var ApiRateLimiterCounter = prometheus.NewCounterVec(
	prometheus.CounterOpts{
		Name: "apiRateLimiterCounter",
		Help: "api限流次数统计.",
	},
	[]string{"method", "path", "limiterType"},
)

var GaugeVec = prometheus.NewGaugeVec(
	prometheus.GaugeOpts{
		Name: "gaugeVec",
		Help: "记录cpu占用率，内存占用率等",
	},
	[]string{"name"},
)

func Init() {
	// Metrics have to be registered to be exposed
	prometheus.MustRegister(ApiCounter, HttpDurations, ApiRateLimiterCounter, GaugeVec)

	go func() {
		for {
			time.Sleep(3 * time.Second)

			// cpu占用比率
			percent, _ := cpu.Percent(time.Second, false)
			GaugeVec.WithLabelValues("cpuUsed").Set(percent[0])
			// 内存占用比率
			memInfo, _ := mem.VirtualMemory()
			GaugeVec.WithLabelValues("memoryUsed").Set(memInfo.UsedPercent)
		}
	}()
}
